const Service = require('egg').Service;
const { Sequelize, Op } = require('sequelize');

class DirinsmsgService extends Service {
    // 添加用service
    async add(msg) {
        const { ctx } = this;
        const result = await ctx.model.Dirinsmsg.create(msg);
        return result;
    }
    // 分页查询用service
    async findList(keywords, pageIndex, pageSize) {
        const { ctx } = this;
        const result = await ctx.model.Dirinsmsg.findAndCountAll({
            where: {
                content: {
                    [Op.like]: '%' + keywords + '%'
                }
            },
            include: [
                {
                    model: ctx.model.Topic,
                    as: 'topic'
                },
            ],
            offset: (pageIndex - 1) * pageSize,
            limit: pageSize
        });
        return result;
    }
    // 根据id查找对应的值
    async findById(id) {
        const { ctx } = this;
        const result = await ctx.model.Dirinsmsg.findOne({
            where:{
                id:id
            },
            include:[
                {
                    model: ctx.model.Topic,
                    as: 'topic'
                },
            ],
        });
        console.log('result.ins_id::::::::::::}::',result.ins_id);
        const result1 = await ctx.model.Teacher.findOne({
            where:{
                id:result.ins_id
            },
        })
        const result2 = await ctx.model.Teacher.findOne({
            where:{
                id:result.dir_id
            },
        })
        const resultFinal = {
            result,
            "dir_teacher":result2,
            "ins_teacher":result1
        }
        return resultFinal;
    }
    // 根据topic_id查找对应的值
    async findByTopicId(topic_id) {
        const { ctx } = this;
        const result = await ctx.model.Dirinsmsg.findOne({
            where:{
                topic_id:topic_id
            },
            order:[
                ['createdAt', 'DESC']
            ],
        });
        console.log('result.ins_id::::::::::::}::',result);
        const result1 = await ctx.model.Teacher.findOne({
            where:{
                id:result.ins_id
            },
        })
        const result2 = await ctx.model.Teacher.findOne({
            where:{
                id:result.dir_id
            },
        })
        const resultFinal = {
            result,
            "dir_teacher":result2,
            "ins_teacher":result1
        }
        return resultFinal;
    }

}
module.exports = DirinsmsgService;
